package cn.yuemouren.suanfa;

/**
 * @Author: Timi
 * @Description: 冒泡排序
 * @Date: 2020/7/23 11:49
 */
public class BubbleSort {

    public static void main(String[] args) {
        int[] arr = {1,7,2,4,5,8,15,9};
        sort(arr,1);
        for (int i : arr)
            System.out.print(i+",");
        System.out.println("-------------");
        sort(arr,2);
        for (int i : arr)
            System.out.print(i+",");
        System.out.println("-------------");
        sort(arr,3);
        for (int i : arr)
            System.out.print(i+",");
        System.out.println("-------------");
        sort(arr,4);
        for (int i : arr)
            System.out.print(i+",");
        System.out.println("-------------");
        sort(arr,5);
        for (int i : arr)
            System.out.print(i+",");
        System.out.println("-------------");
        sort(arr,6);
        for (int i : arr)
            System.out.print(i+",");
        System.out.println("-------------");
        sort(arr,7);
        for (int i : arr)
            System.out.print(i+",");
        System.out.println("-------------");
    }

    /**
     * 排序
     * @param arr 数据
     * @param n 冒泡次数
     */
    private static void sort(int[] arr,int n){
        for(int i = 0; i < n; i++){
            for(int j = 1; j <= n - i; j++){
                if(arr[j] < arr[j - 1]){
                    swap(arr,j,j-1);
                }
            }
        }
    }

    private static void swap(int[] arr,int i,int j){
        int i1 = arr[i];
        arr[i] = arr[j];
        arr[j] = i1;
    }
}
